<template>
  <van-nav-bar
    class="navbar"
    title="课件预览"
    left-text="返回"
    :border="false"
    left-arrow
    @click-left="back"
  />
  <div class="filter">
    <div class="lf">
      <img src="../assets/imgs/icon_filter.png" alt="" /><label for=""
        >筛选</label
      >
    </div>
    <div class="rgt" @click="filterItem">
      <span>{{ selName }}</span>
      <em></em>
    </div>
  </div>
  <van-popup v-model:show="show" round position="bottom">
    <van-cascader
      v-model="cascaderValue"
      title="请选择分类"
      :options="options"
      @close="show = false"
      @finish="onFinish"
    />
  </van-popup>
  <template v-if="worklist.length">
    <div class="works" ref="works">
      <!-- 作品列表 -->

      <div class="work" v-for="it in worklist" :key="it.id">
        <!-- <img :style="{height:ranHeight()}" src="../assets/imgs/a.jpg" alt=""> -->
        <img v-lazy="domain + it.classFileImg" alt="" />
        <p class="name">{{ filterName(it.classFileName) }}</p>
        <p class="desc">
          <span>&nbsp;&nbsp;{{ it.createUserName }}</span>
          <label>查看</label>
        </p>
      </div>
    </div>
  </template>
  <template v-else>
    <div class="emptydata">
      <img src="../assets/imgs/empty_data.png" alt="" />
    </div>
  </template>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
} from "@vue/runtime-core";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Cascader, Popup, Toast } from "vant";
import { throttle } from "../util/util";
import { getCourseList, getCourseType } from "../api/course";
import gloconfig from "../config/index";
export default defineComponent({
  name: "CourseView",
  components: {
    [Cascader.name]: Cascader,
    [Popup.name]: Popup,
  },
  data() {
    return {
      // 这里放一些和业务无关，只需要在页面展示的数据
      domain: gloconfig.api_domain.slice(0, -1),
    };
  },
  setup() {
    let store = useStore();
    let router = useRouter();
    let show = ref(false); //是否显示选择分类弹框
    let works = ref(null); //works ref
    let load = ref(false); //是否数据正在加载
    let isend = ref(false); //是否已经加载完所有数据
    let parm = reactive({
      pageSize: 10, //每页显示数量
      pageNum: 1, //当前页数
      total: 0, //作品总数量
    });
    let worklist = reactive([]);
    let winHeight = document.body.clientHeight; //页面可视高度
    const options = ref([]); //分类数据
    const selName = ref("全部"); //选中的分类名称
    const cascaderValue = ref(""); //选中分类的值
    onBeforeMount(() => {
      courseList(); //初始化课件列表
      coursetype(); //初始化课件分类
    });
    onMounted(() => {
      store.commit("changeFooter", false);
      window.addEventListener("scroll", throttle(scrollPage));
    });
    onBeforeUnmount(() => {
      window.removeEventListener("scroll", scrollPage);
    });
    const filterName = (name) => {
      // 处理课件名称 原 伊河.创美一期1.《红梅赞》 取 最后的作品名
      // return name && name.split('.')[name.split('.').length-1];
      return name && name.match(/《(.*?)》/)[0];
    };
    const courseList = (append = true) => {
      // append: 是否追加到数据后，默认追加
      //课件列表信息
      const parmdata = {};
      parmdata.pageSize = parm.pageSize;
      parmdata.pageNum = parm.pageNum;
      if (cascaderValue.value) {
        parmdata.classFileType = cascaderValue.value;
      }
      load.value=true;
      getCourseList(parmdata).then((res) => {
        load.value=false;
        if (append) {
          worklist.push(...res.data.list);
        } else {
          worklist.splice(0, worklist.length);
          worklist.push(...res.data.list);
        }
        parm.total = res.data.total;
      });
    };
    const coursetype = () => {
      // 课件所有分类
      getCourseType().then((res) => {
        if (res.retCode == 200) {
          let rlt = res.data && res.data.length && resoveTypeData(res.data);
          options.value = rlt;
        }
      });
    };
    const scrollPage = async (evt) => {
      //滚动时判断是否滚动条到了最底部

      let winOffsetHeight = document.body.scrollHeight; //页面滚动条总高度
      let _scrollTop =
        document.body.scrollTop || document.documentElement.scrollTop; // 当前滚动条距离页面顶部高度
      if (_scrollTop + winHeight >= winOffsetHeight - 1) {
        if(isend.value) return; //如果所有数据已经加载完毕，不在继续
        Toast.loading({
          duration: 0, //一直显示
          forbidClick: true, //禁止点击背景层
          // message:'loading。。。'
        });
        parm.pageNum++;
        courseList();
        await nextTick();
        Toast.clear();
        // 计算是否加载完所有数据
        if (parm.pageNum * parm.pageSize > parm.total) {
          isend.value = true;
        }
      }
    };
    const back = () => {
      router.back();
    };
    const filterItem = () => {
      //筛选分类
      show.value = !show.value;
    };

    const resoveTypeData = (data) => {
      // 解析服务器返回的作品分类数据
      const opts = [];
      if (data.length) {
        data.map((dt) => {
          let obj = {};
          obj.text = dt.classFileType; //名称
          obj.value = dt.id; //id
          if (dt.childs) {
            obj.children = [].concat(
              dt.childs instanceof Array ? resoveTypeData(dt.childs) : null
            );
          }
          opts.push(obj);
        });
      }
      return opts;
    };
    const onFinish = ({ value, selectedOptions, tabIndex }) => {
      selName.value = selectedOptions
        .reduce((total, item) => {
          return total + "-" + item.text;
        }, "")
        .replace("-", "");
      show.value = false;
      courseList(false);
    };
    const ranHeight = () => {
      return Math.floor(Math.random() * 100) + 100 + "px";
    };

    return {
      worklist,
      back,
      works,
      load,
      filterItem,
      show,
      options,
      onFinish,
      selName,
      cascaderValue,
      ranHeight, //图片随机高度，模拟数据
      scrollPage,
      filterName,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "../assets/style/common.scss";
.filter {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  border-bottom: 20px solid #f1f1f1;
  .lf {
    font-size: 13PX;
    color: #333;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 40px;
      height: 40px;
      margin-right: 15px;
    }
  }
  .rgt {
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      font-size: 12PX;
      color: $main_clr;
      margin-right: 5px;
    }
    em {
      @include arr_right(12px, 12px);
    }
  }
}
.works {
  padding: 10px 10px 50px;
  column-count: 2;
  column-gap: 20px;
  overflow: auto;
  background: #f1f1f1;
  .work {
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 30px;
    display: flex;
    flex-direction: column;
    break-inside: avoid; /* 不允许半截换行 */
    background: #fff;
    box-shadow: 0 2px 2px 0px #7c7575;
    img {
      width: 100%;
      height: auto;
      border-radius: 10px;
    }
    p.name {
      margin: 10px 0;
      font-size: 15PX;
      color: #111;
      @include textoverflow(1);
    }
    p.desc {
      display: flex;
      justify-content: space-between;
      font-size: 12PX;
      color: #999;
      label {
        color: #4792b0;
      }
    }
  }
}
.emptydata {
  display: flex;
  width: 100%;
  height: 600px;
  justify-content: center;
  align-items: center;
  img {
    width: 196px;
    height: 128px;
    display: block;
  }
}
</style>
